package com.dong.ui.view;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dong.common.constant.PropertiesConst;
import com.dong.common.pojo.ResultVO;
import com.dong.common.util.RequestUtils;
import com.dong.common.view.CommonView;
import com.dong.module.foodmenu.pojo.FoodMenu;
import com.dong.ui.component.CommonDialog;
import com.dong.ui.component.LinkLabel;
import com.dong.ui.constant.RouterConst;
import com.dong.ui.util.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-08-31 15:57
 */
public class FoodDetailFrame extends CommonDialog implements CommonView {
    private JDialog jd = this;

    /*==================组件==================*/
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    // 编辑图标
    private static final int EDIT_WIDTH = 30;
    private static final int EDIT_HEIGHT = 30;

    // 左侧图片
    private static final int IMAGE_WIDTH = WIDTH / 2 - 20;
    private static final int IMAGE_HEIGHT = HEIGHT - 120;

    private JPanel leftPanel;

    private JLabel title;
    private JLabel imageIcon;

    private JPanel RightPanel;

    private JPanel ingredientsLineContainer;
    private JLabel ingredientsTip;
    private JLabel ingredientsBtn;
    private JTextArea ingredientsText;

    private JPanel practiceLineContainer;
    private JLabel practiceTip;
    private JLabel practiceBtn;
    private JTextArea practiceText;


    private JPanel textContainer; // 右侧文本容器
    private JScrollPane rightContainerScrollPane; // 右侧滚动条

    /*==================组件==================*/
    /*==================参数==================*/
    private String id;
    private FoodMenu foodMenu;

    private int rightContainerWidth;
    /*==================参数==================*/
    /*==================标志==================*/
    boolean requestFlag = true;

    /*==================标志==================*/

    @Override
    public void init(Map<String, Object> params) {
        // 设置标题
        setTitle("菜单详情");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        initParams(params);
        initComponent();
        handleView();

        // 设置大小
        setSize(new Dimension(WIDTH, HEIGHT));
        // 设置不可改变大小
        setResizable(false);
        // 设置居中
        setLocationRelativeTo(null);
        // 在显示前处理，否则会被阻塞（模态框），无法加载事件
        handleAction();
        // 设置可见
        setVisible(true);
    }

    @Override
    public void initComponent() {
        Font titleFont = new Font("Stsong", Font.BOLD, 24);
        this.setLayout(new GridLayout(1, 2));

        title = new JLabel(foodMenu.getName());
        title.setFont(titleFont);
        imageIcon = new JLabel(ImageUtils.scaleImage(new ImageIcon(foodMenu.getImage()), IMAGE_WIDTH, IMAGE_HEIGHT));

        ingredientsLineContainer = new JPanel(new FlowLayout(FlowLayout.LEFT));
        ingredientsTip = new JLabel("原料：");
        ingredientsBtn = new LinkLabel(ImageUtils.scaleImage(IconUtils.getFnIcon(PropertiesConst.ICON_KEY_EDIT), EDIT_WIDTH, EDIT_HEIGHT));
        ingredientsBtn.setName("ingredients");
        ingredientsText = new JTextArea(foodMenu.getIngredients());
        ComponentUtils.setTextAreaOnlyRead(ingredientsText, this.getBackground());

        practiceLineContainer = new JPanel(new FlowLayout(FlowLayout.LEFT));
        practiceTip = new JLabel("做法：");
        practiceBtn = new LinkLabel(ImageUtils.scaleImage(IconUtils.getFnIcon(PropertiesConst.ICON_KEY_EDIT), EDIT_WIDTH, EDIT_HEIGHT));
        practiceBtn.setName("practice");
        practiceText = new JTextArea(foodMenu.getPractice());
        ComponentUtils.setTextAreaOnlyRead(practiceText, this.getBackground());



        ingredientsTip.setFont(titleFont);
        practiceTip.setFont(titleFont);

        textContainer = new JPanel();
        rightContainerScrollPane = new JScrollPane(textContainer);
        rightContainerScrollPane.getVerticalScrollBar().setUnitIncrement(20);
        rightContainerScrollPane.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    }

    public void initParams(Map<String, Object> params) {
        if (params != null) {
            id = (String) params.get("id");
        }
        if (StringUtils.isNotBlank(id)) {
            Map<String, Object> requestParams = new HashMap<String, Object>() {{
                put("id", id);
            }};
            ResultVO<FoodMenu> result = (ResultVO<FoodMenu>) RequestUtils.sendRequest("food/get", requestParams);
            if (result.isSuccess()) {
                foodMenu = result.getData();
            } else {
                MessageUtils.showMessageDialog(this, result.getMessage(), "失败", JOptionPane.ERROR_MESSAGE);
            }
        }



        initParams();
    }
    @Override
    public void initParams() {

    }

    @Override
    public void handleView() {

        // 最外层垂直容器
        Box vBox = Box.createVerticalBox();
        // 次外层水平容器
        Box hbox = Box.createHorizontalBox();

        // 左侧容器
        Box leftVBox = Box.createVerticalBox();

        Box titleHBox = Box.createHorizontalBox();
        titleHBox.add(title);

        Box imgHBox = Box.createHorizontalBox();
        imgHBox.add(imageIcon);

        leftVBox.add(titleHBox);
        leftVBox.add(Box.createVerticalStrut(10));
        leftVBox.add(imgHBox);

        // 右侧容器
        Box rightVBox = Box.createVerticalBox();
        Box innerVBox = Box.createVerticalBox();

        ingredientsLineContainer.add(ingredientsTip);
        ingredientsLineContainer.add(ingredientsBtn);
        innerVBox.add(ingredientsLineContainer);
        innerVBox.add(Box.createVerticalStrut(10));
        innerVBox.add(ingredientsText);

        innerVBox.add(Box.createVerticalStrut(30));

        practiceLineContainer.add(practiceTip);
        practiceLineContainer.add(practiceBtn);
        innerVBox.add(practiceLineContainer);
        innerVBox.add(Box.createVerticalStrut(10));
        innerVBox.add(practiceText);

        textContainer.add(innerVBox);
        rightVBox.add(rightContainerScrollPane);

        // 次外层水平容器
        hbox.add(Box.createHorizontalStrut(10));
        hbox.add(leftVBox);
        hbox.add(Box.createHorizontalStrut(5));
        hbox.add(rightVBox);
        hbox.add(Box.createHorizontalStrut(26));

        // 最外层垂直容器
        vBox.add(Box.createVerticalStrut(20));
        vBox.add(hbox);
        vBox.add(Box.createVerticalStrut(20));

        this.add(vBox);
    }

    @Override
    public void handleAction() {
        // 右侧滚动面板大小修改事件（该处为初始化事件）
        rightContainerScrollPaneResizeEvenet();
        // 编辑图标鼠标事件
        editIconMouseEvent();
    }

    /**
     * 编辑图标鼠标事件
     */
    private void editIconMouseEvent() {
        MouseAdapter mouseAdapter = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Object source = e.getSource();
                String name = null;
                if (source instanceof JLabel) {
                    name = ((JLabel) source).getName();
                }
                String text = "";
                switch (name) {
                    case "ingredients":
                        text = ingredientsText.getText();
                        break;
                    case "practice":
                        text = practiceText.getText();
                        break;
                }
                String field = name;
                String finalText = text;
                Map<String, Object> params = new HashMap<String, Object>() {{
                   put("id", id);
                   put("field", field);
                   put("text", finalText);
                   put("parent", jd);
                }};
                RouterUtils.router(RouterConst.VIEW_DETAILEDIT, params);
            }
        };

        ingredientsBtn.addMouseListener(mouseAdapter);
        practiceBtn.addMouseListener(mouseAdapter);
    }

    /**
     * 右侧滚动面板大小修改事件（该处为初始化事件）
     * 1. 使用空白字符串撑开容器
     * 2. 设置单行长度
     */
    private void rightContainerScrollPaneResizeEvenet() {
        rightContainerScrollPane.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                int containerWidth = rightContainerScrollPane.getWidth();
                int barWidth = rightContainerScrollPane.getVerticalScrollBar().getWidth();
                rightContainerWidth = containerWidth - barWidth - 20;
                ingredientsText.setSize(rightContainerWidth, ingredientsText.getHeight());
                practiceText.setSize(rightContainerWidth, practiceText.getHeight());
            }

        });
    }

    /**
     * 设置文本
     * @param field
     * @param text
     */
    public void setText(String field, String text) {
        switch (field) {
            case "ingredients":
                ingredientsText.setText(text);
                break;
            case "practice":
                practiceText.setText(text);
                break;
            default:
        }
    }


}
